#include "stdio.h"
#include <unistd.h>
#include "USBCamera/USBCamera.hpp"

void save_h264_to_file(unsigned char *h264_buffer, unsigned int h264_size, const char *filename) {
    FILE *file = fopen(filename, "wb");
    if (!file) {
        printf("Error opening file for writing: %s\n", filename);
        return;
    }

    // 写入数据到文件
    size_t written_size = fwrite(h264_buffer, 1, h264_size, file);
    if (written_size != h264_size) {
        printf("Error: Only %zu bytes written to file, expected %u bytes\n", written_size, h264_size);
    } else {
        printf("Successfully saved H264 data to %s\n", filename);
    }

    // 关闭文件
    fclose(file);
}


int main(){
    printf("USB Camera Demo\r\n");
    unsigned char yuyv422_buffer[WIDTH * HEIGHT * 2];
    unsigned int yuyv422_size = 0;
    unsigned int h264_size = WIDTH * HEIGHT * 2;
    unsigned char h264_buffer[h264_size];

    unsigned char yuv420_buffer[WIDTH * HEIGHT * 3 / 2];

    bool usb_camera_ret = false;
    USBCamera * usb_camera = USBCamera::getInstance();
    usb_camera_ret = usb_camera->openCamera();
    if(usb_camera_ret == false )    printf("openCamera Error\r\n");

    usb_camera->readFrameBuffer(yuyv422_buffer,&yuyv422_size);

    /* 转化为JPEG */
    const char* output_file = "output.jpg";
    int quality = 100; // 图像质量[0-100]，100表示最高质量

    usb_camera->yuyvToJPEG(yuyv422_buffer, WIDTH, HEIGHT, quality, output_file);
    
    /* yuyv422 -> yuv420 */
    usb_camera->yuyv422ToYUV420(yuyv422_buffer, WIDTH, HEIGHT,yuv420_buffer);

    /* 转化为H264 */
    usb_camera->yuv420ToH264(yuv420_buffer, WIDTH * HEIGHT * 3 / 2, h264_buffer, &h264_size);

    save_h264_to_file(h264_buffer,h264_size,"output.h264");
    return 0;
}